<template>
  <div class="w-full pr-4">
    <div v-if="tagsList.length > 0" class="flex flex-wrap">
      <div v-for="item in tagsList" :key="item.id" class="tag-item flex items-center mb-2">
        <div class="tag-item-label">{{ item.labelName }}</div>
        <div class="tag-item-value">{{ item.itemNameString }}</div>
      </div>
      <div class="mt-0.5">
        <a-button size="small" @click="openTagsModal = true"><FormOutlined /></a-button>
      </div>
    </div>
    <a-button v-else type="primary" ghost @click="openTagsModal = true">添加标签</a-button>
    <TagsModal v-model:open="openTagsModal" :tag-data="tagsList" @success="onSaveTags" />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { FormOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { groupBy } from 'lodash-es'
import { post } from '@/utils/request'
import TagsModal from '@/components/business/TagsModal'

const props = defineProps({
  brId: {
    type: String,
    default: ''
  }
})
const tagsList = ref([])
const labelList = ref([])
const openTagsModal = ref(false)

const getTagsList = async () => {
  if (!props.brId) return
  const { code, data, msg } = await post('/common/label/getLableListByPatientld', { brId: props.brId })
  if (code !== 0) return message.error(msg || '获取标签失败')
  tagsList.value = groupsList(data, 'labelId')
  labelList.value = data.map((tag) => tag.itemId)
}
const groupsList = (list) => {
  const groupedByLabelId = groupBy(list, 'labelId')
  const result = []
  for (const labelId in groupedByLabelId) {
    const items = groupedByLabelId[labelId]
    result.push({
      labelId,
      labelName: items[0].labelName,
      itemId: items.map((item) => item.itemId),
      itemName: items.map((item) => item.itemName),
      itemNameString: items.map((item) => item.itemName).join(', ')
    })
  }
  return result
}
const onSaveTags = async (tags = []) => {
  labelList.value = tags.map((tag) => tag.id)
  tagsList.value = groupsList(tags)
  const res = await post('/operation/opex/doAddLabelList', { brId: props.brId, labelList: labelList.value })
  if (res.code !== 0) return message.error(res.msg)
}

watch(
  () => props.brId,
  (val) => {
    if (val) {
      getTagsList()
    } else {
      tagsList.value = []
      labelList.value = []
    }
  },
  { immediate: true }
)
defineExpose({
  getTagsList
})
</script>
<style lang="less" scoped>
.tag-item {
  margin-right: 8px;
  overflow: hidden;
  font-size: 13px;
  border: 1px solid var(--primary-color);
  border-radius: 6px;
  .tag-item-label {
    padding: 2px 8px;
    color: #fff;
    background-color: var(--primary-color);
  }
  .tag-item-value {
    padding: 2px 8px;
  }
}
</style>
